//
//  AdVViewController.m
//  LoveDraw
//
//  Created by 零零壹 on 2017/7/22.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "AdVViewController.h"
#import "RootViewViewController.h"
#import "LoginViewController.h"
@interface AdVViewController ()

@property(nonatomic, strong) UIImageView *advImage;

@end

@implementation AdVViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    self.advImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:self.advImage];
    self.advImage.image = [UIImage imageNamed:@"launchScreen"];
    [self initAdvView];
    //    NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(change:) userInfo:nil repeats:YES];
    [self performSelector:@selector(change) withObject:nil afterDelay:3];

}

-(void)initAdvView{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"loading1.png"]];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isExit = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    if (isExit) {
                NSLog(@"启动广告图片存在");
        _advImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        [_advImage setImage:[UIImage imageWithContentsOfFile:filePath]];
        [_advImage setUserInteractionEnabled:YES];
        [self.view addSubview:_advImage];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //加载启动广告并保存到本地沙盒，因为保存的图片较大，每次运行都要保存，所以注掉了
            [self getLoadingImage];
        });
    }else{
            NSLog(@"启动广告图片不存在");
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getLoadingImage];
        });
    }
}

-(void)getLoadingImage{

    [RequestManager RequstWithUrl:@"/index.php?g=App&m=Index&a=getIndexAd" parmDic:@{} requestType:RequestGET Success:^(id data)
    {
        NSArray *dataArr = data;

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (dataArr.count>0) {
                NSData *dataM = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KUrl,[dataArr[0] objectForKey:@"ad_file"]]]];

                UIImage *image = [UIImage imageWithData:dataM];

                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

                NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"loading1.png"]];
                // 保存文件的名称
//                    BOOL result = [UIImagePNGRepresentation(filePath) writeToFile: filePath    atomically:YES]; // 保存成功会返回YES
                //                NSLog(@"paths:%@    %@",paths,filePath);
                [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
            }
        });
    } error:^(NSError *error) {

    }];


    
}

-(void)change
{
    UIImageView *imageV = self.advImage;
    
    [UIView beginAnimations:@"" context:nil];   //开始动画
    [UIView setAnimationDelegate:self];
    CGAffineTransform curent =  imageV.transform;
    CGAffineTransform scale = CGAffineTransformScale(curent, 1.2,1.2);
    [UIView setAnimationDuration:1];
    [imageV setTransform:scale];
    [UIView commitAnimations];  //结束动画

    [UIView animateWithDuration:1.2 animations:^{
        imageV.alpha = 0;
    }];

    //其实你知道 烦恼会解决烦恼
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
        if (![[NSUserDefaults standardUserDefaults]boolForKey:@"First"])
        {
            UIViewController *FirstV = [[ NSClassFromString(@"FirstViewController") alloc]init];
            window.rootViewController = FirstV;
        }else
        {
            if ([[NSUserDefaults standardUserDefaults]objectForKey:kAccessToken])
            {
                RootViewViewController *root = [[RootViewViewController alloc]init];
                window.rootViewController = root;
            }else
            {
                LoginViewController *VC = [[LoginViewController alloc]init];
                window.rootViewController = VC;
            }
        }
    });
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
